package com.zhuiYun.project.util;

import com.zhuiYun.project.api.order.service.OrderService;
import com.zhuiYun.project.api.seckill.service.SeckillService;
import com.zhuiYun.project.common.errorCode.CommonException;
import com.zhuiYun.project.common.response.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
* @Description todo 获取当前过期的redis key
* @Author lzy
* @Date 2023/4/12 15:50
*/
@Component
@Transactional
public class RedisKeyExpirationListener  extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    OrderService orderService;

    @Autowired
    SeckillService seckillService;

    /**
     * 监听redis过期key
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String order_orderNumber = message.toString();
        String[] s = order_orderNumber.split("_");
        List<String> list = Arrays.asList(s);
        if (list.size()>1 && list.get(1).equals("ORDER")){
            String orderNumberOrSeckId = list.get(2);
            try {
                // 订单过期未支付，执行订单回滚操作
                orderService.diyOrderRollBack(orderNumberOrSeckId);
            } catch (CommonException e) {
                throw new RuntimeException(e);
            }
        }
        if (list.get(0).equals("DIY")) {
            String orderNumberOrSeckId = list.get(2);
            try {
                // 订单过期未支付，执行订单回滚操作
                orderService.diyOrderRollBack(orderNumberOrSeckId);
            } catch (CommonException e) {
                throw new RuntimeException(e);
            }
        } else if (list.get(0).equals("ORDER")) {
            String orderNumber = list.get(1);
            try {
                // 订单过期未支付，执行订单回滚操作
                orderService.commodityOrderRollBack(orderNumber);
            } catch (CommonException e) {
                throw new RuntimeException(e);
            }
            //如果商品秒杀时间结束
        } else if (list.get(0).equals("SECKILL")) {
            String commId = list.get(1);
            //根据商品id对秒杀商品逻辑删除
            seckillService.ShutDownSeckill(commId);
            //删除秒杀商品缓存
            RedisUtil.del(CommonConstants.COMMODITY_SECKILL_STOCK + commId);

        }
    }
}
